<?php
/**
 * Created by PhpStorm.
 * User: singi
 * Date: 2019/5/5
 * Time: 23:05
 *
 * reference
 * Guzzle: http://docs.guzzlephp.org/en/stable/overview.html
 * DomCrawler: https://symfony.com/doc/current/components/dom_crawler.html
 */

require_once '../lib/start.php';

$config = [
    '出版社' => 'publish',
    'ISBN' => 'isbn',
    '出版时间' => 'publish_date',
];

$path = dirname(__DIR__) . '/data/jd_books_i.log';
$i = file_get_contents($path) ? file_get_contents($path) : 10000001;

for (; $i < PHP_INT_MAX; $i++) {
    $book = get_book($i);
    if (!$book) {
        continue;
    }

    if (!$db->get('books', ['isbn' => $book['isbn']])) {
        $db->insert('books', $book);
    }
    var_dump("{$i}:{$book['title']}-{$book['isbn']}");

    file_put_contents($path, $i);
}

function get_book($book_num)
{
    global $client, $config;
    $book_insert = [];
    try {
        $crawler = $client->request('GET', "https://item.jd.com/{$book_num}.html");
        $book_insert['title'] = trim($crawler->filter('#name .sku-name')->text());
        $book_insert['author'] = trim($crawler->filter('#p-author')->text());
        $book_insert['cover'] = trim($crawler->filter('#spec-n1 > img')->attr('src'));

        $books_infos = $crawler->filter('#parameter2 li')->each(function ($node) {
            return $node->text();
        });

        if ($books_infos) {
            foreach ($books_infos as $books_info) {
                $arr = explode('：', $books_info);
                if (isset($config[$arr[0]])) {
                    $book_insert[$config[$arr[0]]] = str_replace([' ', '\n'], '', trim($arr[1]));
                }
            }
        }
        $book_insert['create_time'] = $book_insert['update_time'] = date('Y-m-d H:i:s');
    } catch (Exception $e) {
        var_dump($e);
    }

    return $book_insert;
}

